package com.jlnk.gsondemo.adapter;

import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.jlnk.gsondemo.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class HotSearchAdapter extends RecyclerView.Adapter<HotSearchAdapter.HotSearchViewHolder> {
    private JSONArray hotSearchList;

    public HotSearchAdapter(JSONArray hotSearchList) {
        this.hotSearchList = hotSearchList;
    }

    @NonNull
    @Override
    public HotSearchViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_hot_search, parent, false);
        return new HotSearchViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull HotSearchViewHolder holder, int position) {
        try {
            JSONObject hotSearch = hotSearchList.getJSONObject(position);
            holder.textViewRank.setText(String.valueOf(position + 1));
            holder.textViewTitle.setText(hotSearch.getString("title"));
            holder.textViewHotValue.setText(hotSearch.getString("hotValue"));
            holder.textViewLink.setText(hotSearch.getString("link"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {
        return hotSearchList.length();
    }

    static class HotSearchViewHolder extends RecyclerView.ViewHolder {
        TextView textViewRank;
        TextView textViewTitle;
        TextView textViewHotValue;
        TextView textViewLink;

        public HotSearchViewHolder(@NonNull View itemView) {
            super(itemView);
            textViewRank = itemView.findViewById(R.id.textViewRank);
            textViewTitle = itemView.findViewById(R.id.textViewTitle);
            textViewHotValue = itemView.findViewById(R.id.textViewHotValue);
            textViewLink = itemView.findViewById(R.id.textViewLink);

            itemView.setOnClickListener(v -> {
                String url = textViewLink.getText().toString();
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                itemView.getContext().startActivity(intent);
            });
        }
    }
}